import { _decorator, Component, instantiate, JsonAsset, Prefab, resources, SpriteAtlas, UITransform } from 'cc';
import { LayerManager } from '../Basic/Manager/LayerManager';
import { OpenLoadModel_Ins } from '../Basic/UI/OpenLoadPanel';
import { DataMgr } from '../Basic/Manager/DataManager';
import { GameManager } from '../Basic/Manager/GameManager';
import { BasePrefab, LoadingBundle, SoundCode } from '../Basic/Config/BaseEnum';
import { MainModel_Ins } from '../Game/Main/MainModel';
import { LogUtil } from '../Util/LogUtil';
import { Tables } from '../Data/Types';
import { ImagePath } from '../Game/Config/GameEnum';
import { LoadingManager } from '../Basic/Manager/LoadingManager';
import { CallBackHandler } from '../Basic/Model/PoolObj/CallBackHandler';
import { MultiPlatform } from '../Basic/Model/Platform/MultiPlatform';
const { ccclass } = _decorator;

@ccclass('GameScene')
export class GameScene extends Component {
  async initGameScene() {
    //初始化数据
    // DataMgr.init();
    // RedDotManager.Ins().initRedDotData();
    // BattleManager.Ins().init();
    // EquipmentModel_Ins.initEquipmentData();
    // PassAwardModel_Ins.initSectionData();
    // let index = 1;
    // const passData = GameData.globalParams.get(GlobalParams.gameSectionPassCount);
    // passData.forEach((count) => {
    //   if (count > 0) index++;
    // });
    // index = index >= passData.length ? passData.length : index;
    // if (GameData.globalParams.get(GlobalParams.gameSection) != index) GameData.changeGlobalAttr(GlobalParams.gameSection, index, true);
    // GameData.changeGlobalAttr(GlobalParams.gameSection, 1, true);

    // HandlerManager.Ins().handle(HandleCode.ARENA_LEADERBOARD_PLAYER, { type: 'common' });

    // await MainModel_Ins.changeGameModel(GameData.globalParams.get(GlobalParams.gameSection));
    const node = instantiate(LoadingManager.Ins().getResource(BasePrefab.ui_controller));
    this.node.parent.addChild(node);
    GameManager.UIController = node;
    GameManager.GameTransform = node.getComponent(UITransform);
    LayerManager.Singleton.init();
    LayerManager.Singleton.initLoading(OpenLoadModel_Ins.loadRes);
    // GameData.changePlayerAttr(PlayerParams.isNovice, false);

    MainModel_Ins.Show();
  }

  private speed: number = 1000;
  private stepRate: number = 0;
  private tempRate: number = 0;
  private loadingRate: number = 0;
  private loadingRateMax: number = 0;
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  private stepFuncs: Function[] = [];

  protected onLoad(): void {
    MultiPlatform.Ins().platformSelect();
  }

  protected onEnable(): void {
    this.stepRate = 0;
    this.tempRate = 0;
    this.loadingRate = 0;
    this.stepFuncs = [this.loadTables, this.initTables, this.initServerData, this.loadGameRes, this.Complete];
    this.loadingRateMax = this.stepFuncs.length;
    this.stepFuncs[this.stepRate].call(this);
    // GravityModel.Ins().track(GEEvent.LOGIN, { isFirst: GameData.playerParams.get(PlayerParams.isNovice) });
    // MultiPlatform.Ins().platformUnit.requestSubscribeMessage();
  }

  protected update(dt: number): void {
    if (this.stepRate >= this.loadingRateMax) return;
    if (this.tempRate < this.loadingRate) {
      this.tempRate += dt * this.speed;
      if (this.tempRate > this.loadingRate) {
        this.tempRate = this.loadingRate;
      }
    } else {
      return;
    }
    // const rate = (this.stepRate + this.tempRate) / this.loadingRateMax;
    // this.barLab.string = `${(rate * 100).toFixed(this.toFixed)}%`;
    // this.bar.progress = rate > 1 ? 1 : rate;
    if (this.tempRate >= 1 && this.loadingRate >= 1) {
      this.tempRate = 0;
      this.loadingRate = 0;
      this.stepRate++;
      if (this.stepRate < this.loadingRateMax) {
        this.stepFuncs[this.stepRate].call(this);
      }
    }
  }

  protected onProgress = (rate) => {
    this.loadingRate = rate;
  };

  /** 加载表数据 */
  private loadTables() {
    LogUtil.i('加载表数据......');
    const bundle = LoadingManager.Ins().getBundle(LoadingBundle.BaseBundle);
    const arr = bundle.getDirWithPath('data');
    const loadRes = [];
    for (let i = 0; i < arr.length; i++) {
      loadRes.push(arr[i].path);
    }
    LoadingManager.Ins().loadResByBundle(LoadingBundle.BaseBundle, loadRes, this.onProgress.bind(this));
  }

  // /** 初始化表数据，链接服务器 */
  private initTables() {
    LogUtil.i('初始化表数据，链接服务器......');
    // const task = Task.createSync();
    // task.add((next) => {
    DataMgr.tables = new Tables(this.loadTable);
    this.onProgress(1);
    // next();
    // });
    // task.add((next) => {
    //   // HandlerManager.Ins().init();
    //   next();
    // });
    // task.start(this.onProgress.bind(this, 1));
  }

  /** 获取服务器数据 */
  private initServerData() {
    //设置时间控制器
    // GameManager.Singleton.init();
    this.onProgress(1);
  }

  /** 加载主界面资源，初始化游戏场景 */
  private loadGameRes() {
    LogUtil.i('加载主界面资源，初始化游戏场景......');
    const loadPanel = [
      // 通用加载界面资源
      OpenLoadModel_Ins.loadRes,
      MainModel_Ins.loadRes,
      // UI控制器
      BasePrefab.ui_controller,
    ];

    // const loadRes = [ImagePath.bottle_lego_atlas];
    // resources.load<Prefab>(loadPanel, (err, data) => {
    //   data.forEach((d) => {
    //     ResourceManager_Ins.addRes(loadPanel.filter((l) => l.indexOf(d.name) != -1)[0], d);
    //   });
    //   resources.load<SpriteAtlas>(loadRes, (err, data) => {
    //     data.forEach((d) => {
    //       ResourceManager_Ins.addRes(loadRes.filter((l) => l.indexOf(d.name) != -1)[0], d);
    //     });
    //     this.onProgress(1);
    //   });
    // });
    // LoadingManager.Ins().loadResByBundle(LoadingBundle.BaseBundle, loadPanel, this.onProgress);
    LoadingManager.Ins().loadResource(
      loadPanel,
      this.onProgress
      // CallBackHandler.pop(() => {
      //   LoadingManager.Ins().loadResource(loadRes, this.onProgress);
      // }, this)
    );
  }

  /** 加载表格数据 */
  loadTable(jsonName: string) {
    const str = LoadingBundle.BaseBundle + '/data/' + jsonName;
    const bundle: JsonAsset = LoadingManager.Ins().getResource<JsonAsset>(str);
    return bundle.json;
  }

  private async Complete() {
    //加载完成
    console.log('加载完成');
    this.initGameScene();
  }
}
